package com.example.listdetail;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Arrays;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class URLImageParser implements Html.ImageGetter {
    Context c;
    View container;

    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param t
     * @param c
     */
    public URLImageParser(View t, Context c) {
        this.c = c;
        this.container = t;
    }

    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
                new ImageGetterAsyncTask( urlDrawable);
        String src="";
        if(source.startsWith("http")){
                src=source;
        }
        else{
            src="http:"+source;
        }
        asyncTask.execute(src);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;
        final  File photoPath =ContextHolder.getContext().getExternalCacheDir();

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            String fileName=this.formatFileName(source);
            try
            {
                File f = new File(photoPath+"/"+fileName);
                if(f.exists())
                {
                    return drawableLocalFile(photoPath+"/"+fileName);
                }
                else{
                    return fetchDrawable(source);
                }

            }
            catch (Exception e)
            {
                return null;
            }

        }

        @Override
        protected void onPostExecute(Drawable result) {
            if(result!=null){
                urlDrawable.setBounds(0, 0, result.getIntrinsicWidth(), 0 + result.getIntrinsicHeight());
                urlDrawable.drawable = result;
                TextView contentDetail= URLImageParser.this.container.findViewById(R.id.content_detail);
                contentDetail.setText(contentDetail.getText());
            }

        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
                InputStream is = fetch(urlString);
                Drawable drawable = Drawable.createFromStream(is, "src");
                drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0+drawable.getIntrinsicHeight());
                return drawable;
            } catch (Exception e) {
                return null;
            }
        }
        /**
         * 本地图片
         * @author Susie
         */
        private Drawable drawableLocalFile (String source) {
            try {

                // 获取本地图片
                Drawable drawable = Drawable.createFromPath(source);
                // 必须设为图片的边际,不然TextView显示不出图片
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                Log.d("drawableLocalFile", "绘制?读取本地图片");
                // 将其返回
                return drawable;
            }
            catch (Exception e) {
                return null;
            }
        }

        /**
         * 拼接文件名
         * @param urlString
         * @return
         */
        private  String formatFileName (String urlString ){
            String[] stringArr=urlString.split("/");
            String fileLastName=stringArr[stringArr.length-1];
            String fileName;
            if(fileLastName.endsWith(".jpg")||fileLastName.endsWith(".png")){
                fileName=fileLastName;
            }
            else{
                fileName=fileLastName=".png";
            }
            return fileName;
        }
        //写入本地
        private  void  writeFile(String urlString,InputStream inputStream){

            String fileName =this.formatFileName(urlString);
            try {

//                File photoPath = Environment.getDownloadCacheDirectory();
             //   File photoPath =ContextHolder.getContext().getFilesDir();

                //https://blog.csdn.net/losefrank/article/details/53464646 关于文件存储，内部存储，外部存储说明
              //  File photoPath =ContextHolder.getContext().getExternalCacheDir();
                //创建文件对象，用来存储新的图像文件
                File file = new File(photoPath+"/"+fileName);
                FileOutputStream fops = new FileOutputStream(file);
                byte[] buffer = new byte[1024];

                int len = 0;
                while( (len=inputStream.read(buffer)) != -1 ){
                    fops.write(buffer, 0, len);
                }
                fops.flush();
                fops.close();
                System.out.println("绘制?图片已经写入"+photoPath+"/"+fileName);
            } catch (Exception e) {
                Log.d("ee", "写入异常");
                e.printStackTrace();
            }
        }
        private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            final OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(urlString)
                    .build();

            Response response = client.newCall(request).execute();
            InputStream bodyStr=response.body().byteStream();
            this.writeFile(urlString,bodyStr);
            return bodyStr=response.body().byteStream();
        }
    }
}